package com.example.admin.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.admin.bean.LoginUserDetails;
import com.example.admin.constants.RedisKeyConstants;
import com.example.admin.utils.JwtUtil;
import com.example.admin.utils.StringUtils;
import com.example.admin.utils.UserThreadLocal;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Value("${zhyl.securet}")
    private String securitykey;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入线程拦截器");
        String uuid = request.getHeader("token");
        if (StringUtils.isEmpty(uuid)){
            return true;
        }
        System.out.println("进入其它界面");
        String newtoken = stringRedisTemplate.opsForValue().get(RedisKeyConstants.LOGIN_USER_TOKEN + uuid);
        Claims claims = JwtUtil.parseJWT(securitykey,newtoken);
        String user = (String)claims.get("user");
        LoginUserDetails loginUserDetails = JSONObject.parseObject(user, LoginUserDetails.class);
        UserThreadLocal.setSubject(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("释放掉当前线程");
        UserThreadLocal.removeSubject();


    }
}
